all files / src/ isolate.ts

100% Statements 19/19
100% Branches 12/12
100% Functions 5/5
100% Lines 19/19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541× 1×     1×       6× 8× 1×     5×     2×       9× 1×   8×   6×                 2×       6× 1×   5×   5× 2×   3×              
import xs, {Stream} from 'xstream';
import {adapt} from '@cycle/run/lib/adapt';
import {HTTPSource, RequestOptions, RequestInput} from './interfaces';
 
function arrayEqual(
  requestNamespace: Array<any>,
  sourceNamespace: Array<any>
): boolean {
  for (let i = 0; i < sourceNamespace.length; i++) {
    if (requestNamespace[i] !== sourceNamespace[i]) {
      return false;
    }
  }
  return true;
}
 
export function isolateSource(
  httpSource: HTTPSource,
  scope: string | null
): HTTPSource {
  if (scope === null) {
    return httpSource;
  }
  return httpSource.filter(
    (request: RequestOptions) =>
      Array.isArray(request._namespace) &&
      arrayEqual(
        request._namespace,
        (httpSource as any)._namespace.concat(scope)
      ),
    scope
  );
}
 
export function isolateSink(
  request$: Stream<RequestInput | string>,
  scope: string | null
): Stream<RequestInput> {
  if (scope === null) {
    return request$;
  }
  return adapt(
    xs.fromObservable<RequestInput | string>(request$).map(req => {
      if (typeof req === 'string') {
        return {url: req, _namespace: [scope]} as RequestOptions;
      }
      return {
        ...req,
        _namespace: [scope, ...(req._namespace || [])]
      };
    })
  );
}